package com.simen.hellobytes.rpc.socket.udp.multisocket;

import com.simen.hellobytes.socket.UDPMultiSocket;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.NetworkInterface;
import java.net.SocketException;

/**
 * author: SimenHi
 * create time: 2020-12-14 11:09
 * description:
 */
public class RMIUDPMultisocketService {

    private String group;
    private int port;

    private MessageListener messageListener;
    private UDPMultiSocket udpMultiSocket;
    private NetworkInterface networkInterface;

    public interface MessageListener {
        void onReceiveMessage(byte[] data, int length, DatagramPacket client);
    }

    public RMIUDPMultisocketService(String group,
                                    int port,
                                    NetworkInterface networkInterface,
                                    MessageListener messageListener) {
        this.group = group;
        this.port = port;
        this.networkInterface=networkInterface;
        this.messageListener = messageListener;
    }

    public void launch() throws SocketException, AlreadyLaunchServiceException {
            if(udpMultiSocket!=null && udpMultiSocket.isRunning()){
                throw new AlreadyLaunchServiceException("service already launch");
            }
            udpMultiSocket = new UDPMultiSocket(group, port);
            udpMultiSocket.setNetworkInterface(networkInterface);
            udpMultiSocket.setMessageListener(new com.simen.hellobytes.socket.helper.MessageListener<byte[], DatagramPacket>() {
                @Override
                public int onMessage(byte[] buf, int length, DatagramPacket clientInfo) throws IOException {
                    if (messageListener != null) {
                        messageListener.onReceiveMessage(buf, length, clientInfo);
                        return com.simen.hellobytes.socket.helper.MessageListener.KEEP;
                    }

                    return com.simen.hellobytes.socket.helper.MessageListener.DISCONNECT;
                }
            });
            udpMultiSocket.listen();
    }

    public void close(){
        if(udpMultiSocket!=null){
            udpMultiSocket.closeImmediately();
            udpMultiSocket=null;
        }
    }

    public String getGroup() {
        return group;
    }

    public void setGroup(String group) {
        this.group = group;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public MessageListener getMessageListener() {
        return messageListener;
    }

    public void setMessageListener(MessageListener messageListener) {
        this.messageListener = messageListener;
    }
}
